import 'package:flutter/material.dart';

import '71_life_state.dart';

/// 监听 Widget 的声明周期
/// 使用 RouteObserver
/// 后面在网上找了个封装好的

main() {
  runApp(RenApp());
}

final RouteObserver<Route<dynamic>> routeObserver = RouteObserver();

class RenApp extends StatelessWidget {
  const RenApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      navigatorObservers: [routeObserver, lifeObserver],
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with RouteAware {
  @override
  void initState() {
    super.initState();
  }

  @override
  void didPush() {
    debugPrint("------> didPush");
    super.didPush();
  }

  @override
  void didPop() {
    debugPrint("------> didPop");
    super.didPop();
  }

  @override
  void didPopNext() {
    debugPrint("------> didPopNext");
    super.didPopNext();
  }

  @override
  void didPushNext() {
    debugPrint("------> didPushNext");
    super.didPushNext();
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this); //取消订阅
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    routeObserver.subscribe(this, ModalRoute.of<dynamic>(context)!); //订阅
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('stream builder')),
      body: Center(
        child: TextButton(
          onPressed: () {
            Navigator.of(context).push(MaterialPageRoute(builder: (ctx) {
              return const Page2();
            }));
          },
          child: Text('跳转'),
        ),
      ),
    );
  }
}

class Page2 extends StatefulWidget {
  const Page2({Key? key}) : super(key: key);

  @override
  State<Page2> createState() => _Page2State();
}

class _Page2State extends LifeState<Page2> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('第二个界面')),
      body: Center(
        child: TextButton(
          child: Text('跳转'),
          onPressed: (){
            Navigator.of(context).push(MaterialPageRoute(builder: (ctx){
              return const Page3();
            }));
          },
        ),
      ),
    );
  }

  @override
  void onPaused() {
    debugPrint('Page2 onPaused');
  }

  @override
  void onResume() {
    debugPrint('Page2 onResume');
  }
}

class Page3 extends StatefulWidget {
  const Page3({Key? key}) : super(key: key);

  @override
  State<Page3> createState() => _Page3State();
}

class _Page3State extends State<Page3> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('第三个界面')),
    );
  }
}

